package com.lushixiang.controller.file;

import com.lushixiang.base.BaseResHead;
import com.lushixiang.base.BaseResponse;
import com.lushixiang.facade.FileFacade;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Paths;

import static com.lushixiang.StaticVariables.commonFilePlace;
import static com.lushixiang.enums.CommonRespEnum.UPLOAD_ERROR;
import static com.lushixiang.enums.CommonRespEnum.WELL_DONE;

@Slf4j
@Component
public class uploadController implements FileFacade {
    @Override
    public BaseResponse<String> uploadFiles(MultipartFile[] files) {
        log.info("进入File上传处理controller");
        BaseResponse<String> response = new BaseResponse<>();
        BaseResHead head = new BaseResHead();
        String localFileDir = commonFilePlace;

        for (MultipartFile file : files) {
            try{
                file.transferTo(Paths.get(localFileDir));
            }catch (IOException ioException){
                log.info("文件上传发生IO异常{}",ioException.toString());
                head.setResCode(UPLOAD_ERROR.getCode());
                head.setResMsg(UPLOAD_ERROR.getMsg());
                response.setResHead(head);
                return response;
            }
        }
        head.setResCode(WELL_DONE.getCode());
        head.setResMsg(WELL_DONE.getMsg());
        response.setResHead(head);
        return response;
    }
}
